import { Router, Route, Link, BrowserRouter, Switch, useHistory } from 'react-router-dom'
import { React, useEffect, useState } from 'react';
import { Layout, Menu, Breadcrumb, Space, Statistic, Row, Col, Card, Typography, List, Image, Radio } from 'antd';
import axios from 'axios';
import { Redirect } from 'react-router'
import SubjectOneTest from './subjectOneTest'
import { checkLogin } from '../../utils/loginUtils/loginMethod'
import api from '../../utils/requestUtils/apiConfig'
import { message, Button, Progress, Modal, notification, Alert } from 'antd';

let rightQuestionList = []
let errorQuestionList = []
let rightQuestionId = []
let errorQuestionId = []
let answerMap = new Map()
export default ({
    pictureUrl,
    setPictureUrl
}) => {
    const [rightQuestion, setRightQuestion] = useState([])
    const [errorQuestion, setErrorQuestion] = useState([])
    // const [rightQuestionId, setRightQuestionId] = useState([])
    // const [errorQuestionId, setErrorQuestionId] = useState([])


    const { Title, Text, Link } = Typography;
    const [data, setData] = useState([])
    const [title, setTitle] = useState('');
    const [id, setId] = useState([])
    const [a, setA] = useState('');
    const [b, setB] = useState('');
    const [c, setC] = useState('');
    const [d, setD] = useState('');
    const [answer, setAnswer] = useState('');
    const [index, setIndex] = useState(0);
    const [questionInfo, setQuestionInfo] = useState([])
    const [questionNum, setQuestionNum] = useState(0)
    const [dataSource, setDataSource] = useState([])
    const [process, setPorcess] = useState(0)
    /************examInfo var */
    const { Countdown } = Statistic;
    const [examInfoData, setExamInfoData] = useState([])
    const [deadline, setDeadline] = useState(Date.now() + 1000 * 60 * 45);
    /*******弹窗 */
    const [submitVisible, setSubmitVisible] = useState(false)
    const [submitLoading, setSubmitLoading] = useState(false)
    const [beSubmitVisible, setBeSubmitVisible] = useState(false)
    const [beSubmitLoading, setBeSubmitLoading] = useState(false)
    const [type, setType] = useState(3)
    //
    const [examQueLoading, setExamQueLoading] = useState(false)
    const history = useHistory()
    //试题信息请求发送
    const subjectOneExam = async () => {
        setExamQueLoading(true)
        let type = 0
        const examType = sessionStorage.getItem('examType')
        if (examType == '小车') {
            type = 0
            setType(type)
        }
        else if (examType == '货车') {
            type = 1
            setType(type)
        }
        else {
            type = 2
            setType(type)
        }
        const params = {
            type: type
        }
        axios({
            url: api.subjectOneExam,
            method: 'get',
            headers: '',
            params: params,
        }).then((result) => {
            const res = result.data.data
            setData(res)

            if (res.size != 0) {
                const question = res[0]
                setTitle(question.question)
                if (question.optionThree !== '') {
                    setQuestionInfo([

                        `A：${question.optionOne}`,
                        `B：${question.optionTwo}`,
                        `C：${question.optionThree}`,
                        `D：${question.optionFour}`,
                    ])
                }
                else {
                    setQuestionInfo([

                        `A:${question.optionOne}`,
                        `B:${question.optionTwo}`,
                        `                        `,
                        `                         `,

                    ])
                }
                setExamQueLoading(false)
                setId(question.id)
                setA(question.optionOne)
                setB(question.optionTwo)
                setC(question.optionThree)
                setD(question.optionFour)
                setAnswer(question.answer)
                if (question.picture !== '') {
                    setPictureUrl('http://image.jsyst.cn/images201305/' + question.picture)
                } else {
                    setPictureUrl('')
                }

            }

        })
    }
    const optionSet = (num) => {
        if (data.size != 0) {
            const question = data[num]
            setIndex(num)
            setTitle(question.question)
            if (question.optionThree == '') {
                setQuestionInfo([

                    `A:${question.optionOne}`,
                    `B:${question.optionTwo}`,
                    `                       `,
                    `                       `,
                ])
            }
            else {
                setQuestionInfo([

                    `A：${question.optionOne}`,
                    `B：${question.optionTwo}`,
                    `C：${question.optionThree}`,
                    `D：${question.optionFour}`,
                ])
            }
            setId(question.id)
            setA(question.optionOne)
            setB(question.optionTwo)
            setC(question.optionThree)
            setD(question.optionFour)
            setAnswer(question.answer)
            if (question.picture !== '') {
                setPictureUrl('http://image.jsyst.cn/images201305/' + question.picture)
            } else {
                setPictureUrl('')
            }
        }
    }

    const next = () => {
        if (questionNum + 1 > 99) {
            message.error("已经是最后一题")
        } else {

            optionSet(questionNum + 1)
            setQuestionNum(questionNum + 1)
        }
    }
    const previous = () => {
        if (questionNum - 1 < 0) {

            message.error("已经是第一题")
        }
        else {
            optionSet(questionNum - 1)
            setQuestionNum(questionNum - 1)

        }
    }

    const OptionButton = () => {
        const isChoose = rightQuestion.includes(questionNum) || errorQuestion.includes(questionNum)

        if (c == '') {
            return (
                <>
                    <Space>
                        <span>选项：</span>
                        <Button onClick={() => answerCheck(1)} disabled={isChoose}>A</Button>
                        <Button onClick={() => answerCheck(2)} disabled={isChoose}>B</Button>
                    </Space>
                </>

            )
        }
        else {
            return (
                <>
                    <Space>

                        <span>选项：</span>
                        <Button onClick={() => answerCheck(1)} disabled={isChoose}>A</Button>
                        <Button onClick={() => answerCheck(2)} disabled={isChoose}>B</Button>
                        <Button onClick={() => answerCheck(3)} disabled={isChoose}>C</Button>
                        <Button onClick={() => answerCheck(4)} disabled={isChoose}>D</Button>
                    </Space>
                </>
            )
        }

    }
    const MyChoose = () => {
        const myChoose = answerMap.get(questionNum)
        if (myChoose == 1){
            return <Text>你的选择是：A</Text>
        }
        else if(myChoose == 2){
            return <Text>你的选择是：B</Text>
        }
        else if(myChoose == 3){
            return <Text>你的选择是：C</Text>
        }
        else if(myChoose == 4){
            return <Text>你的选择是：D</Text>
        }
        else {
            return <Text>你的选择是：</Text>
        }

    }
    //试题判断
    const answerCheck = (ans) => {

        if (ans == answer) {
            /**
             * 选择了正确的答案后要进行的事情：
             * 
             * 2、记录作完该题的信息，改变该试题在概览的样式：red 错误， green 正确  blue ：没做的
             * 3、统计错题
             * 1、跳到下一题
             * 
             */

            //将正确题号压入数组重
            rightQuestionList.push(questionNum)
            rightQuestionId.push(id)

            if (!(questionNum + 1 > 99)) {

                //跳转下一题
                optionSet(questionNum + 1)
                setQuestionNum(questionNum + 1)
            }



        }
        else {
            //将错误题号压入数组重
            errorQuestionList.push(questionNum)
            errorQuestionId.push(id)
            if (!(questionNum + 1 > 99)) {
                //跳转下一题
                optionSet(questionNum + 1)
                setQuestionNum(questionNum + 1)
            }
        }
        //将题号与对于答案压入数组
        answerMap.set(questionNum, ans)
        setPorcess(rightQuestionList.length + errorQuestionList.length)
        setRightQuestion(rightQuestionList)
        setErrorQuestion(errorQuestionList)
        question()


    }
    const submit = () => {
        //交卷
        /**
         * 提交信息：用户id ， 错误题目， 正确题目 分数
         */
        const params = {
            userId: localStorage.getItem('id') || sessionStorage.getItem('id'),
            rightQuestion: rightQuestionId.toString(),
            errorQuestion: errorQuestionId.toString(),
            score: rightQuestionId.length,
            type: type
        }
        axios({
            url: api.examResSubmit,
            method: 'post',
            headers: '',
            params: {},
            data: params
        }).then((response) => {
            const result = response.data
            if (result.message === 'success') {
                message.success({
                    content: `提交成功，本次成绩${rightQuestionList.length}分，即将跳转到个人中心查看成绩`,
                    onClose: () => { history.push("/selfCenter") }

                })
            }
            else if (result.message === 'error') {
                message.error("提交失败")
            }

            setSubmitLoading(false)
        })

    }
    const DialogInfo = () => {

        if (process == 100) {
            return (
                <Text type="danger">以做完全部试题，是否交卷</Text>

            )
        }
        else {
            return (
                <Text type="danger">还有未做完的题，是否交卷</Text>
            )
        }

    }


    /*******************examInfo Method */

    function onFinish() {
        message.success({
            content: `考试时间已结束，成绩${rightQuestionList.length}分即将提交本次试题`,
            style: {
                marginTop: '20vh',
            },
            onClose: submit()
        });
    }

    const changeQuestion = (no) => {
        console.log(no)
    }
    // 循环放置题目按钮
    const question = () => {
        const questions = []
        for (let i = 0; i < 100; i++) {
            if (rightQuestion.includes(i)) {
                questions.push(<Radio.Button style={{ backgroundColor: 'green' }} value={i} >{i + 1}</Radio.Button>)
            }
            else if (errorQuestion.includes(i)) {
                questions.push(<Radio.Button style={{ backgroundColor: 'red' }} value={i} >{i + 1}</Radio.Button>)
            }
            else {
                questions.push(<Radio.Button value={i} >{i + 1}</Radio.Button>)
            }
        }
        setDataSource(questions)
    }
    //试题浏览 属性生成
    const getExamInfoDataSource = () => {
        const res = []
        for (let index = 0; index < 100; index++) {
            res.push({
                no: questionNum,
                state: 0
            })
        }
        setExamInfoData(res)
    }
    //点击单选按钮跳转到某一题目
    const jumpQuestion = (e) => {
        setQuestionNum(e.target.value)
        optionSet(e.target.value)

    }



    useEffect(() => {
        console.log(deadline)
    }, [deadline])

    //时间时间结束时提示
    useEffect(() => {
        //test
        // setTimeout(()=>{
        // }, 2000);
        setTimeout(() => {
            notification.warning({
                message: <Alert message="距考试结束还有10分钟，请抓紧时间答题！" type="warning" />,
                placement: 'topLeft'
            });
        }, 2100000);
    }, [])

    useEffect(() => {
        subjectOneExam()
        getExamInfoDataSource()
        question()
    }, [])

    // useEffect(() => {
    //     console.log(process, "process")
    //     setPorcess(rightQuestionList.length + errorQuestionList.length)
    // }, [rightQuestion, errorQuestion])

    useEffect(() => {
        if (process == 100) {
            setSubmitVisible(true)
        }
    }, [process])

    return (
        <>
            <Space>
                <Space

                    direction='vertical'
                >
                    <Card
                        title='考试题目'
                        style={{ width: 800 }}
                        loading={examQueLoading}
                        actions={[
                            <MyChoose/>,
                            <OptionButton />,
                            <Space>
                                <Button
                                    onClick={previous}
                                    disabled={questionNum == 0 ? true : false}
                                >上一题</Button>
                                <Button onClick={next}
                                    disabled={questionNum == 99 ? true : false}
                                >下一题</Button>
                            </Space>

                        ]}
                    >

                        <Space direction='vertical' style={{ height: 250 }}>
                            <Title level={5}>{questionNum + 1}、{title}</Title>

                            <List
                                size="small"
                                dataSource={questionInfo}
                                renderItem={item => <List.Item>{item}</List.Item>}

                            />
                        </Space>
                    </Card>
                    <Card
                        title='图片信息'
                        style={{ width: 800, height: 300 }}
                    >
                        <Image
                            src={pictureUrl}
                        >

                        </Image>

                    </Card>
                </Space>

                <Space
                    direction='vertical'
                >
                    <div></div>
                    <Card
                        title='剩余时间'
                        style={{ marginTop: 35 }}
                    >
                        <Space
                            size='large'
                        >
                            <Countdown
                                style={{ marginLeft: 50 }}
                                value={deadline}
                                onFinish={onFinish}
                                valueStyle={{ color: "red" }}
                                format='m分s秒'
                            />
                        进度：<Progress type="circle" percent={process} width={80} />
                        </Space>

                    </Card>
                    <Card
                        title='题目概览'
                        // style={{ width: 300 }}
                        actions={[
                            <>
                                <Button type="primary" danger size='large' onClick={() => { setSubmitVisible(true) }}> 交卷</Button>
                                <Button onClick={() => { onFinish() }}>Test考试时间结束</Button>
                            </>

                        ]}
                    >
                        <Radio.Group
                            value={questionNum}
                            optionType="button"
                            buttonStyle="solid"
                            size="small"
                            onChange={(e) => { jumpQuestion(e) }}
                        >
                            <List
                                size='small'
                                grid={{ column: 10 }}
                                dataSource={dataSource}
                                renderItem={item => <List.Item>{item}</List.Item>}
                            >
                            </List>
                        </Radio.Group>
                    </Card>



                </Space>
            </Space>
            {/* 主动交卷 */}
            <Modal
                centered
                visible={submitVisible}
                confirmLoading={submitLoading}
                onOk={() => {
                    setSubmitLoading(true)
                    submit()
                    setSubmitVisible(false)
                }}
                onCancel={() => setSubmitVisible(false)}
                okText="交卷"
                cancelText="取消"
            // width={1000}
            >
                <DialogInfo />
            </Modal>
            {/* 时间结束被动交卷 */}
        </>
    )
}